package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.dtos.LoginDto;
import com.heima.user.dto.ResponseLoginUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.model.common.user.dtos.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseLoginUser login(LoginDto dto) {

        if (StringUtils.isBlank(dto.getPhone()) || StringUtils.isBlank(dto.getPassword())) {
            return new ResponseLoginUser(AppJwtUtil.getToken(0L), new ApUser());
        }
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!apUser.getPassword().equals(
                DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes())
        )) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        apUser.setSalt("");
        apUser.setPassword("");
        return new ResponseLoginUser(AppJwtUtil.getToken(apUser.getId().longValue()), apUser);
    }
}